﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace ShortLink.Common.Utils
{
    public static class CommonUtil
    {
        // 获取客户端 IP 地址
        public static string GetIpAddr(HttpContext context)
        {
            string ipAddress = context.Request.Headers["X-Forwarded-For"].FirstOrDefault() ??
                               context.Request.Headers["Proxy-Client-IP"].FirstOrDefault() ??
                               context.Request.Headers["WL-Proxy-Client-IP"].FirstOrDefault() ??
                               context.Connection.RemoteIpAddress?.ToString();

            if (ipAddress == "127.0.0.1" || string.IsNullOrEmpty(ipAddress))
            {
                try
                {
                    ipAddress = Dns.GetHostEntry(Dns.GetHostName())
                                    .AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork)?.ToString();
                }
                catch
                {
                    ipAddress = "Unknown";
                }
            }

            return ipAddress?.Split(',')[0] ?? "Unknown";
        }

        // 获取全部请求头
        public static Dictionary<string, string> GetAllRequestHeaders(HttpContext context)
        {
            return context.Request.Headers.ToDictionary(h => h.Key, h => h.Value.ToString());
        }

        // MD5 加密
        public static string MD5Encrypt(string data)
        {
            using var md5 = MD5.Create();
            byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(data));
            return BitConverter.ToString(hashBytes).Replace("-", "").ToUpper();
        }

        // 获取指定长度的验证码随机数
        public static string GetRandomCode(int length)
        {
            const string digits = "0123456789";
            return new string(Enumerable.Range(0, length).Select(_ => digits[Random.Shared.Next(digits.Length)]).ToArray());
        }

        // 获取当前时间戳（毫秒级）
        public static long GetCurrentTimestamp() => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

        // 生成 UUID（32 位）
        public static string GenerateUUID() => Guid.NewGuid().ToString("N");

        // 获取指定长度的随机字符串（字母 + 数字）
        private const string AllCharNum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        public static string GetStringNumRandom(int length)
        {
            return new string(Enumerable.Range(0, length).Select(_ => AllCharNum[Random.Shared.Next(AllCharNum.Length)]).ToArray());
        }

        // 发送 JSON 响应
        public static async Task SendJsonMessage(HttpResponse response, object obj)
        {
            response.ContentType = "application/json; charset=utf-8";
            await response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(obj));
            await response.Body.FlushAsync();
        }
    }

}
